<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            clearable
            @clear="getUserList()"
            v-model="params.query"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 数据展示 -->
    <el-table :data="userList" stripe size="mini" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="50px"></el-table-column>
      <el-table-column align="center" prop="username" label="姓名"></el-table-column>
      <el-table-column align="center" prop="email" label="邮箱"></el-table-column>
      <el-table-column align="center" prop="mobile" label="电话"></el-table-column>
      <el-table-column align="center" prop="role_name" label="角色"></el-table-column>
      <el-table-column align="center" label="状态">
        <!-- 状态插槽  scope可以获取当前行的所有值-->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="userStateChanged(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <!-- 操作按钮组 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editUserDialog(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeUser(scope.row.id)"
          ></el-button>
          <!-- 按钮提示 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="isEnterable"
          >
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
          </el-tooltip>`
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="params.pagenum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="params.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totals"
    ></el-pagination>

    <!-- 添加用户的dialog -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的dialog -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 给用户赋角色 -->
    <el-dialog title="分配角色" :visible.sync="editRoleDialogVisible" width="50%" @close="setRoleDialogVisible">
      <span>
        <div>
          <p>当前用户名称：{{userInfo.username}}</p>
          <p>当前用户角色：{{userInfo.role_name}}</p>
          <p>分配角色：
            <el-select v-model="selectedRoleId" filterable placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义校验邮箱
    var checkEmail = (rule, value, cb) => {
      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (reg.test(value)) {
        cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    // 自定义校验手机号
    var checkPhone = (rule, value, cb) => {
      const reg = /^1[3456789]\d{9}$/
      if (reg.test(value)) {
        cb()
      }
      cb(new Error('请输入正确手机号'))
    }
    return {
      params: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userList: [],
      totals: 0,
      isEnterable: false,
      addDialogVisible: false,
      editDialogVisible: false,
      // 添加表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 面包屑
      levelList: null,
      // 控制角色对话框的显示与隐藏
      editRoleDialogVisible: false,
      // 分配角色的用户信息
      userInfo: {},
      // 角色列表
      roleList: [],
      selectedRoleId: ''
    }
  },
  created () {
    // 页面创建时加载数据
    this.getUserList()
  },
  methods: {
    // 获取用户列表数据
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.params
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.totals = res.data.total
      this.pagenum = res.pagenum
    },
    // 页面大小事件
    handleSizeChange (pagesize) {
      this.params.pagesize = pagesize
      this.getUserList()
    },
    // 当前页面
    handleCurrentChange (pagenum) {
      this.params.pagenum = pagenum
      this.getUserList()
    },
    // 监听用户状态改变
    async userStateChanged (userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    // 添加用户
    addUser () {
      // 校验用户是否合法
      this.$refs.addFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // 添加用户
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        // 添加成功清除值，重新刷新列表，关闭对话框
        this.$message.success('添加成功')
        this.$refs.addFormRef.resetFields()
        this.getUserList()
        this.addDialogVisible = false
      })
    },
    // 展示用户信息
    async editUserDialog (id) {
      this.editDialogVisible = true
      // 获取用户个人信息
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取个人信息失败')
      }
      this.editForm = res.data
    },
    // 修改用户
    editUser () {
      // 校验表单
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.$refs.editFormRef.resetFields()
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    async removeUser (id) {
      // 提示用户是否删除
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(confirmRes)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      // 执行删除
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 展示角色对话框
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 展示之前获取当前用户已经拥有的角色
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      this.editRoleDialogVisible = true
    },
    async saveUserRole () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新用户角色失败')
      }
      // 更新成功刷新用户列表
      this.getUserList()
      // 关闭对话框
      this.editRoleDialogVisible = false
    },
    // 关闭分配角色对话框，重置用户信息
    setRoleDialogVisible () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.item {
  margin: 4px;
}
</style>
